/**
 * 时间处理转换StrToDate
 */
export function strToDate(dateStr: string) {
  const timeStamp = Date.parse(dateStr.replaceAll('-', '/'));
  return timeStamp ? new Date(timeStamp) : null;
}

/**
 * 计算年龄
 */
export function calculateAge(
  birthDateStr: string,
): undefined | number | string {
  if (typeof birthDateStr !== 'string' || birthDateStr.trim() === '') {
    console.error('输入必须是一个有效的日期字符串');
    return '-';
  }

  let birthDate: Date;
  // 尝试使用不同的日期格式进行解析
  if (birthDateStr.includes('-')) {
    birthDate = new Date(birthDateStr.replaceAll('-', '/'));
  } else if (birthDateStr.includes('/')) {
    birthDate = new Date(birthDateStr);
  } else {
    console.error(
      '%o,输入的日期字符串格式无效，应使用 yyyy-MM-dd 或 yyyy/MM/dd 格式',
      birthDateStr,
    );
    return '-';
  }

  if (Number.isNaN(birthDate.getTime())) {
    console.error('输入的日期字符串无法解析为有效日期');
    return '-';
  }

  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (
    monthDiff < 0 ||
    (monthDiff === 0 && today.getDate() < birthDate.getDate())
  ) {
    age--;
  }
  return age;
}
